<template>
  <div id="mqtt">
    <div>
      <video-player  class="video-player-box"
                     ref="videoPlayer"
                     v-bind:options="playerOptions"
                     :playsinline="true"
                     >
      </video-player>      
    </div>
    <div>
      <swiper :options="swiperOption">
        <swiper-slide class="swiper-slide" v-for="(item,index) in slide" :key="index">
          我是第{{item}}个轮播图           
        </swiper-slide>
        <div class="swiper-pagination"  slot="pagination"></div>   <!-- 分页 -->
        <div class="swiper-button-prev" slot="button-prev"></div>  <!-- 箭头左 --> 
        <div class="swiper-button-next" slot="button-next"></div>  <!-- 箭头右 -->
      </swiper>
    </div>    
    <router-link :to="'/Chart'">图表</router-link>    
    <router-link :to="''" @click.native="openlayer()">打开一个窗口</router-link>    
    <router-link :to="''" @click.native="camerashot()">拍照</router-link>   
    <router-link :to="''" @click.native="screenshot()">屏幕截图</router-link>   
    <div>
    <input type="text" id="snedTxt6" v-model="snedTxt6" />
    <button id="sendb6" v-on:click="say2()">Post发送Vue.js消息</button>
    </div>  
    <div>
      <el-switch
        v-model="switchvalue"
        active-color="#13ce66"
        inactive-color="#ff4949"
        @change="switchchange()">
      </el-switch>
      <el-rate v-model="ratevalue" @change="ratechange()"></el-rate>
    </div>  
    <el-image 
      style="width: 100px; height: 100px"
      v-bind:src="demoimg" 
      v-bind:preview-src-list="srcList">
    </el-image>    
    <h1>{{ msg }}</h1>
    <vue-justgage ref="g1" id="g1" ></vue-justgage>
    <div >    
  <p v-for="message in messages">{{ message }}</p>
  </div>
  </div>
</template>

<script>
import mqtt from 'mqtt';
import 'swiper/dist/css/swiper.css'
import { swiper, swiperSlide } from 'vue-awesome-swiper'

export default {
  name: 'mqtt',
  data () {
    return {
      msg: '欢迎来到vue.js的世界',
      messages:[],
      switchvalue:true,
      ratevalue:5,
      demoimg:'',
      srcList:[],
      snedTxt6:'',
      mqttclient:null,
      justgageclient: null,
      slide: [1, 2, 3, 4, 5],
      //设置属性
      swiperOption: {
        //显示分页
        pagination: {
          el: '.swiper-pagination',
          clickable: true //允许分页点击跳转
        },
        //设置点击箭头
        navigation: {
          nextEl: '.swiper-button-next', 
          prevEl: '.swiper-button-prev'
        },
        //自动轮播
        autoplay: {
          delay: 3000
        },
        //开启循环模式
        loop: true,
        //开启鼠标滚轮控制Swiper切换
        mousewheel: true
      },
      playerOptions: {
        // videojs options
        muted: true,
        autoplay: true, //如果true,浏览器准备好时开始回放。
        controls: false,
        language: 'zh-CN',
        preload: 'auto',
        loop: true,
        aspectRatio: '16:9',
        notSupportedMessage: '此视频暂无法播放，请稍后再试',
        playbackRates: [0.7, 1.0, 1.5, 2.0],
        sources: []
      }            
    }
  },
  mounted: function() { 
    this.InitMqtt();
  }, 
  components: {
    swiper,
    swiperSlide
  },  
  methods: {
    InitMqtt: function () {
      var self = this;

     var options = {
    //mqtt客户端的id，这里面应该还可以加上其他参数，具体看官方文档
      clientId: 'mqttjs_' + Math.random().toString(16).substr(2, 8),
      //username:'admin',
      //password:'112233',
      will: {
        topic: 'loc/jjolie',
        payload: '连接断开',
        qos: 0,
        retain: true
      }      
    }    

      this.mqttclient = mqtt.connect("ws://127.0.0.1:9001/mqtt",options) // you add a ws:// url here
      this.$GLOBAL.mqttclient = this.mqttclient;

      //建立连接
      this.mqttclient.on('connect', function () {
        console.log("mqtt connect success!")
        self.mqttclient.publish('loc/jjolie','连接上线',{ qos: 2, retain: false })
      })
      
      //如果连接错误，打印错误
      this.mqttclient.on('error', function (err) {
        console.log(err)
        self.mqttclient.end()
      })

      //如果client订阅主题成功，那么这里就是当接收到自己订阅主题的处理逻辑
      this.mqttclient.on('message', function (topic, message) {
        // message is Buffer,此处就是打印消息的具体内容
        console.info(message.toString());

         try{ 
          var params = JSON.parse( message.toString() );
          self.messages.push(params.name);
          self.msg = params.name;

          if(params.camera_img) {
            self.demoimg = params.camera_img;            
          }

          if(params.screenshot_img) {
            self.demoimg = params.screenshot_img;            
          }

          self.srcList.push(self.demoimg);
          self.justgageclient.refresh(params.jp);

         // self.$router.go(0);

          self.playerOptions.sources = [{
              type: "video/mp4",
              src: params.video
            }];

         }catch(exception){
          console.info(exception.message);
         } 
      })

      var maxx = 100;

      this.justgageclient = this.$refs.g1.draw({
          id: "g1",
          value: 50,
          min: 0,
          max: maxx,
          titleMinFontSize:5,
          title: "Score",
          label: "",
          pointer: true,
          textRenderer: function (val) {
              return (val + '/' + maxx);
          },
          onAnimationEnd: function () {
              console.log('f: onAnimationEnd()');
          }
      });
    },
    say2: function () {

       // var salt=CryptoJS.enc.Utf8.parse("salt");  //盐         
       // var iter=901;  //迭代次数         
      //  var mi=CryptoJS.PBKDF2(this.snedTxt6, salt,
       //           { keySize: parseInt(4),
       //           iterations: parseInt(iter) }
        //          );

        var qtt = {}; //定义消息（可以为字符串，对象等）
        qtt.name = this.snedTxt6;

       this.mqttclient.publish('loc/jjolie',JSON.stringify(qtt),{ qos: 2, retain: false })
    },
    openlayer: function () {
        let that=this;
        this.$layer.confirm('确定归还该琴房吗?', {
          btn: ['确定','取消']     //按钮
        }, function(){           //点击确定访问后台
          that.$layer.closeAll();
        }, function(){    //点击取消则中断操作
          that.$layer.closeAll();
          that.$layer.open({type:3,content:'请等待...',time:5,shade: true,shadeClose: false});
        })
    },
    switchchange: function() {
        var self = this;
        console.info(self.switchvalue);
        this.$layer.confirm(self.switchvalue ? 'Hello' : 'World', {
          btn: ['确定']     //按钮
        });
    },
    ratechange: function() {
      var self = this;
      this.$layer.confirm(self.ratevalue, {
        btn: ['确定']     //按钮
      });
    },
    camerashot: function() {
        var self = this;

        //订阅主题 presence
        this.mqttclient.subscribe('super/machine/camera/32', function (err) {
          if (!err) {
             var qtt = {}; //定义消息（可以为字符串，对象等）
             qtt.machineid = 34;
             qtt.playerid = 32;

             self.mqttclient.publish('super/machine/camera',JSON.stringify(qtt),{ qos: 0, retain: false })
          }else{
          //打印错误
            console.log(err)
          }
        })     
    },
    screenshot: function() {
        var self = this;

        //订阅主题 presence
        this.mqttclient.subscribe('super/machine/screenshot/32', function (err) {
          if (!err) {
             var qtt = {}; //定义消息（可以为字符串，对象等）
             qtt.machineid = 34;
             qtt.playerid = 32;

             self.mqttclient.publish('super/machine/screenshot',JSON.stringify(qtt),{ qos: 0, retain: false })
          }else{
          //打印错误
            console.log(err)
          }
        })     
    },           
  }     
}
</script>

<style>
#app {
  font-family: 'Avenir', Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}

h1, h2 {
  font-weight: normal;
}

ul {
  list-style-type: none;
  padding: 0;
}

li {
  display: inline-block;
  margin: 0 10px;
}

a {
  color: #42b983;
}

.swiper-slide {
  width: 100%;
  height: 100px;
  line-height: 100px;
  font-size: 50px;
  text-align: center;
  background-color: rosybrown;
}

</style>
